<?php
namespace app\api\model;

use app\common\model\BaseModel;

/**
 * 会员模型
 * Class Member
 * @package app\api\model
 */
class Member extends BaseModel
{
    // 表名
    protected $name = 'members';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = false; // 关闭自动时间戳，手动处理
    
    /**
     * 生成会员编号
     * @return string
     */
    private function generateMemberNo()
    {
        // 生成格式：M + 年月日 + 6位随机数
        return 'M' . date('Ymd') . mt_rand(100000, 999999);
    }
    
    /**
     * 微信小程序登录
     * @param string $code 小程序登录code
     * @param array $userInfo 用户信息
     * @return array
     */
    public function wxLogin($code, $userInfo = [])
    {
        // 微信配置信息
        $config = config('wechat');
        $appId = $config['app_id'];
        $appSecret = $config['app_secret'];
        
        // 请求微信接口获取openid和session_key
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
        $response = $this->httpGet($url);
        $result = json_decode($response, true);
        
        if (!isset($result['openid'])) {
            return ['code' => 500, 'msg' => '微信登录失败：' . ($result['errmsg'] ?? '未知错误')];
        }
        
        $openid = $result['openid'];
        $sessionKey = $result['session_key'];
        $unionid = isset($result['unionid']) ? $result['unionid'] : '';
        
        // 查询是否已存在该用户
        $member = self::where('openid', $openid)->find();
        
        if (!$member) {
            // 新用户，创建记录
            $member = new self;
            $member->openid = $openid;
            $member->member_no = $this->generateMemberNo(); // 生成会员编号
            $member->phone = 'wx_' . substr($openid, -10); // 临时手机号，避免为空
            
            // 如果有用户信息，则保存
            if (!empty($userInfo) && is_array($userInfo)) {
                $member->name = $userInfo['nickName'] ?? '微信用户';
                $member->avatar = $userInfo['avatarUrl'] ?? '';
                $member->gender = $userInfo['gender'] ?? 0;
            } else {
                $member->name = '微信用户'; // 确保name字段有值
            }
            
            $member->register_date = date('Y-m-d H:i:s');
            $member->updated_at = date('Y-m-d H:i:s');
            $member->save();
        } else {
            // 已存在用户，更新登录信息
            $updateData = ['last_login_time' => date('Y-m-d H:i:s')];
            $updateData['updated_at'] = date('Y-m-d H:i:s');
            
            // 如果有用户信息，则更新
            if (!empty($userInfo) && is_array($userInfo)) {
                $updateData['name'] = $userInfo['nickName'] ?? $member->name;
                $updateData['avatar'] = $userInfo['avatarUrl'] ?? $member->avatar;
                $updateData['gender'] = $userInfo['gender'] ?? $member->gender;
            }
            
            $member->save($updateData);
        }
        
        // 生成token
        $token = $this->generateToken($member->id, $openid);
        
        // 返回用户信息和token
        return [
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'userInfo' => $member->getInfoData(),
                'session_key' => $sessionKey
            ]
        ];
    }
    
    /**
     * 手机号登录
     * @param string $phone 手机号
     * @param string $openid 微信openid
     * @param array $userInfo 用户信息
     * @return array
     */
    public function login($phone, $openid, $userInfo = [])
    {
        if (empty($openid)) {
            return ['code' => 400, 'msg' => '参数错误：缺少openid'];
        }
        
        // 如果没有提供手机号，使用临时手机号
        if (empty($phone)) {
            $phone = 'wx_' . substr($openid, -10);
        }
        
        // 先查询是否有该手机号的用户
        $member = self::where('phone', $phone)->find();
        
        if (!$member) {
            // 再查询是否有该openid的用户
            $member = self::where('openid', $openid)->find();
            
            if (!$member) {
                // 新用户，创建记录
                $member = new self;
                $member->phone = $phone;
                $member->openid = $openid;
                $member->member_no = $this->generateMemberNo(); // 生成会员编号
                
                // 设置默认值，确保必填字段有值
                if (!empty($userInfo['name'])) {
                    $member->name = $userInfo['name'];
                } else {
                    // 如果没有提供名称，使用手机号作为默认名称
                    $member->name = substr_replace($phone, '****', 3, 4);
                }
                
                $member->gender = isset($userInfo['gender']) ? $userInfo['gender'] : 1;
                
                if (!empty($userInfo['avatar'])) {
                    $member->avatar = $userInfo['avatar'];
                }
                
                $member->register_date = date('Y-m-d H:i:s');
                $member->updated_at = date('Y-m-d H:i:s');
                $member->save();
            } else {
                // 已存在openid的用户，更新手机号
                // 如果原来的手机号是临时的，才更新
                if (strpos($member->phone, 'wx_') === 0 && $phone && strpos($phone, 'wx_') !== 0) {
                    $member->phone = $phone;
                }
                $member->updated_at = date('Y-m-d H:i:s');
                $member->save();
            }
        } else {
            // 已存在手机号的用户，检查openid是否匹配
            if ($member->openid != $openid) {
                // 更新openid
                $member->openid = $openid;
            }
            
            // 更新登录信息和用户信息
            $updateData = [
                'last_login_time' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            // 如果有用户信息，则更新
            if (!empty($userInfo)) {
                if (!empty($userInfo['name'])) {
                    $updateData['name'] = $userInfo['name'];
                }
                
                if (!empty($userInfo['avatar'])) {
                    $updateData['avatar'] = $userInfo['avatar'];
                }
                
                if (isset($userInfo['gender'])) {
                    $updateData['gender'] = $userInfo['gender'];
                }
            }
            
            $member->save($updateData);
        }
        
        // 生成token
        $token = $this->generateToken($member->id, $openid);
        
        // 返回用户信息和token
        return [
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'userInfo' => $member->getInfoData()
            ]
        ];
    }
    
    /**
     * 生成用户认证token
     * @param int $userId 用户ID
     * @param string $openid 用户openid
     * @return string
     */
    private function generateToken($userId, $openid)
    {
        $tokenData = [
            'user_id' => $userId,
            'openid' => $openid,
            'timestamp' => time()
        ];
        
        // 生成token
        $token = md5(json_encode($tokenData) . config('api.token_salt'));
        
        // 将token存入缓存，有效期30天
        cache('api_token_' . $token, $userId, 86400 * 30);
        
        return $token;
    }
    
    /**
     * 获取用户信息数据
     * @return array
     */
    public function getInfoData()
    {
        return [
            'id' => $this->id,
            'member_no' => $this->member_no,
            'name' => $this->name,
            'avatar' => $this->avatar,
            'gender' => $this->gender,
            'phone' => $this->phone,
            'email' => $this->email,
            'balance' => $this->balance,
            'is_verified' => $this->is_verified,
            'member_level' => $this->member_level,
            'register_date' => $this->register_date,
            'last_login_time' => $this->last_login_time
        ];
    }
    
    /**
     * 发送HTTP GET请求
     * @param string $url 请求URL
     * @return string
     */
    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }
} 